import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_country_website/model/View.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:http/http.dart' as http;
import '../conf/configure.dart';
import '../model/Product.dart';
import 'scenic_detail_page.dart';
import 'product_detail.dart';


class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  List<View> views = [];
  List<Product> products = [];

  @override
  void initState() {
    getViews();
    getProducts(1);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFe5e8f5),
      appBar: AppBar(
        title: Text('首页'),
        centerTitle: true,
        elevation: 0,
      ),
      body: Column(
        children: [
          views.isNotEmpty ? swiper() : SizedBox(),
          Expanded(child: goodsList())
        ],
      )
    );
  }

  void getViews() async {
    String url = 'http://' + Config.IP + ':' + Config.PORT + '/?action=getViews';

    var res = await http.get(Uri.parse(url));
    String body = res.body;
    debugPrint("body: $body");

    Map bodyMap = jsonDecode(body);
    List item = bodyMap['items'];
    item.forEach((element) {
      views.add(View.fromJson(element));
    });
    setState(() {});
  }

  void getProducts(int page) async {
    String url = 'http://' + Config.IP + ':' + Config.PORT + '/?action=getProducts&page=$page';

    var res = await http.get(Uri.parse(url));
    String body = res.body;
    debugPrint("body: $body");

    Map bodyMap = jsonDecode(body);
    List item = bodyMap['items'];
    item.forEach((element) {
      products.add(Product.fromJson(element));
    });
  }

  Widget swiper() {
    return Container(
      height: 200,
      child: Swiper(
        itemBuilder: (BuildContext context,int index){
          return Hero(
              tag: views[index].title!,
              child: Image.network(views[index].image.toString(),fit: BoxFit.fill,)
          );
        },
        layout: SwiperLayout.TINDER,
        itemCount: views.length,
        pagination: SwiperPagination(
            builder: SwiperPagination.dots
        ),
        onTap: (tapIndex) {
          Navigator.push(context, MaterialPageRoute(builder: (context)
          => ScenicDetailPage(detail: views[tapIndex])));
        },
        autoplay: true,
        // control: new SwiperControl(),
      ),
    );
  }

  Widget goodsList() {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 10.0,
          mainAxisSpacing: 10.0,
          childAspectRatio: 1/1
      ),
      itemCount: products.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return productItem(index);
      },
    );
  }

  Widget productItem(int index) {
    return GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context)
          => GoodsDetail(product: products[index])));
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Container(
          // padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            color: Colors.white,
            // boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 2, spreadRadius: 1)]
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.network(products[index].image ?? '', fit: BoxFit.fitWidth),
              SizedBox(height: 5),
              Container(
                padding: EdgeInsets.only(left: 5, right: 5, top: 10),
                child: Row(
                  children: [
                    Expanded(child: Text(
                        products[index].name ?? '',
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2, style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold), textAlign: TextAlign.center)
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

}

